import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';

import '../models/dateline_event.dart';
import '../providers/dateline_providers.dart';

/// 添加或编辑时间线事件的对话框
class AddDatelineEventDialog extends ConsumerStatefulWidget {
  /// 要编辑的事件（如果为null则表示添加新事件）
  final DatelineEvent? eventToEdit;

  /// 构造函数
  const AddDatelineEventDialog({Key? key, this.eventToEdit}) : super(key: key);

  @override
  ConsumerState<AddDatelineEventDialog> createState() => _AddDatelineEventDialogState();
}

class _AddDatelineEventDialogState extends ConsumerState<AddDatelineEventDialog> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _locationController = TextEditingController();
  
  late DateTime _eventDate;
  late TimeOfDay _eventTime;
  late DatelineEventType _eventType;
  List<String> _photoUrls = [];
  List<File> _selectedImages = [];
  bool _isLoading = false;

  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    super.initState();
    
    // 如果是编辑模式，则使用现有事件的数据初始化表单
    if (widget.eventToEdit != null) {
      final event = widget.eventToEdit!;
      _titleController.text = event.title;
      _descriptionController.text = event.description ?? '';
      _locationController.text = event.location ?? '';
      
      _eventDate = event.eventTime;
      _eventTime = TimeOfDay(hour: event.eventTime.hour, minute: event.eventTime.minute);
      _eventType = event.eventType;
      _photoUrls = List.from(event.photoUrls ?? []);
    } else {
      // 添加新事件，使用默认值
      final now = DateTime.now();
      _eventDate = now;
      _eventTime = TimeOfDay.now();
      _eventType = DatelineEventType.familyGathering;
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    _locationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isEdit = widget.eventToEdit != null;
    final datelineTypesAsync = ref.watch(datelineTypesProvider);
    
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 8,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          color: Colors.white,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 头部
            Container(
              decoration: BoxDecoration(
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(16),
                  topRight: Radius.circular(16),
                ),
                gradient: LinearGradient(
                  colors: [
                    _eventType.color.withOpacity(0.8),
                    _eventType.color.withOpacity(0.6),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
              ),
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      _eventType.icon.icon,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          isEdit ? '编辑时间线事件' : '添加时间线事件',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          _eventType.displayName,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.white.withOpacity(0.8),
                          ),
                        ),
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: Container(
                      padding: const EdgeInsets.all(4),
                      child: Icon(
                        Icons.close,
                        color: Colors.white.withOpacity(0.8),
                        size: 20,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 内容
            Flexible(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Form(
                  key: _formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 事件类型选择器
                      _buildEventTypeField(datelineTypesAsync),
                      
                      // 标题输入框
                      _buildFormField(
                        label: '事件标题',
                        child: TextFormField(
                          controller: _titleController,
                          decoration: _buildInputDecoration('请输入事件标题'),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请输入事件标题';
                            }
                            return null;
                          },
                        ),
                      ),
                      
                      // 地点输入框
                      _buildFormField(
                        label: '事件地点',
                        child: TextFormField(
                          controller: _locationController,
                          decoration: _buildInputDecoration('请输入事件地点（可选）'),
                        ),
                      ),
                      
                      // 日期和时间选择器
                      Row(
                        children: [
                          Expanded(
                            child: _buildFormField(
                              label: '事件日期',
                              child: GestureDetector(
                                onTap: () => _selectEventDate(context),
                                child: Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.grey[300]!),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Row(
                                    children: [
                                      Icon(Icons.calendar_today, size: 18, color: _eventType.color),
                                      const SizedBox(width: 8),
                                      Text(
                                        DateFormat('MM-dd').format(_eventDate),
                                        style: const TextStyle(fontSize: 14),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: _buildFormField(
                              label: '事件时间',
                              child: GestureDetector(
                                onTap: () => _selectEventTime(context),
                                child: Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.grey[300]!),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Row(
                                    children: [
                                      Icon(Icons.access_time, size: 18, color: _eventType.color),
                                      const SizedBox(width: 8),
                                      Text(
                                        _eventTime.format(context),
                                        style: const TextStyle(fontSize: 14),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      
                      // 描述输入框
                      _buildFormField(
                        label: '事件描述',
                        child: TextFormField(
                          controller: _descriptionController,
                          decoration: _buildInputDecoration('请输入事件描述（可选）'),
                          maxLines: 3,
                        ),
                      ),
                      
                      // 照片选择区域
                      _buildFormField(
                        label: '照片（最多9张）',
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (_selectedImages.isNotEmpty || _photoUrls.isNotEmpty)
                              SizedBox(
                                height: 100,
                                child: ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  itemCount: _selectedImages.length + _photoUrls.length + 1,
                                  itemBuilder: (context, index) {
                                    // 添加照片按钮
                                    if (index == _selectedImages.length + _photoUrls.length) {
                                      return Padding(
                                        padding: const EdgeInsets.only(right: 8),
                                        child: _buildAddPhotoButton(),
                                      );
                                    }
                                    
                                    // 显示已选择的本地图片
                                    if (index < _selectedImages.length) {
                                      return Padding(
                                        padding: const EdgeInsets.only(right: 8),
                                        child: _buildImageItem(
                                          imageFile: _selectedImages[index],
                                          onRemove: () => _removeLocalImage(index),
                                        ),
                                      );
                                    }
                                    
                                    // 显示已有的网络图片
                                    final urlIndex = index - _selectedImages.length;
                                    return Padding(
                                      padding: const EdgeInsets.only(right: 8),
                                      child: _buildImageItem(
                                        imageUrl: _photoUrls[urlIndex],
                                        onRemove: () => _removeNetworkImage(urlIndex),
                                      ),
                                    );
                                  },
                                ),
                              )
                            else
                              _buildAddPhotoButton(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // 底部按钮
            Container(
              decoration: BoxDecoration(
                border: Border(top: BorderSide(color: Colors.grey[200]!)),
              ),
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                    ),
                    child: const Text('取消'),
                  ),
                  const SizedBox(width: 12),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _saveEvent,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _eventType.color,
                      padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: _isLoading
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : Text(
                            isEdit ? '保存' : '添加',
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                          ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 构建事件类型选择器
  Widget _buildEventTypeField(AsyncValue<List<DatelineEventType>> typesAsync) {
    return _buildFormField(
      label: '事件类型',
      child: typesAsync.when(
        data: (types) {
          if (types.isEmpty) {
            return _buildTypeEmptyState();
          }

          var currentType = _eventType;
          if (!types.contains(_eventType)) {
            currentType = types.first;
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (!mounted) return;
              setState(() {
                _eventType = currentType;
              });
            });
          }

          return DropdownButtonFormField<DatelineEventType>(
            decoration: _buildInputDecoration('选择事件类型'),
            value: currentType,
            items: types.map((type) {
              return DropdownMenuItem<DatelineEventType>(
                value: type,
                child: Row(
                  children: [
                    Icon(type.icon.icon, color: type.color, size: 18),
                    const SizedBox(width: 8),
                    Text(type.displayName),
                  ],
                ),
              );
            }).toList(),
            onChanged: (value) {
              if (value != null) {
                setState(() {
                  _eventType = value;
                });
              }
            },
          );
        },
        loading: () => _buildTypeLoadingState(),
        error: (error, stack) => _buildTypeErrorState(error),
      ),
    );
  }

  /// 构建事件类型加载状态
  Widget _buildTypeLoadingState() {
    return Container(
      height: 56,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: const SizedBox(
        width: 20,
        height: 20,
        child: CircularProgressIndicator(strokeWidth: 2),
      ),
    );
  }

  /// 构建事件类型错误状态
  Widget _buildTypeErrorState(Object error) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.redAccent),
        color: Colors.redAccent.withOpacity(0.05),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '加载事件类型失败',
            style: TextStyle(
              color: Colors.redAccent,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            '$error',
            style: const TextStyle(color: Colors.redAccent),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
              onPressed: () => ref.refresh(datelineTypesProvider),
              child: const Text('重试'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空数据状态
  Widget _buildTypeEmptyState() {
    return Container(
      height: 56,
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: const Text(
        '暂无可用的事件类型',
        style: TextStyle(color: Colors.grey),
      ),
    );
  }

  /// 构建表单字段
  Widget _buildFormField({
    required String label,
    required Widget child,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: Text(
            label,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
        ),
        child,
        const SizedBox(height: 16),
      ],
    );
  }
  
  /// 构建输入框装饰
  InputDecoration _buildInputDecoration(String hintText) {
    return InputDecoration(
      hintText: hintText,
      hintStyle: TextStyle(color: Colors.grey[400]),
      filled: true,
      fillColor: Colors.grey[50],
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: _eventType.color, width: 2),
      ),
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
    );
  }

  /// 构建添加照片按钮
  Widget _buildAddPhotoButton() {
    final totalImages = _selectedImages.length + _photoUrls.length;
    final canAddMore = totalImages < 9;
    
    return InkWell(
      onTap: canAddMore ? _showImageSourceDialog : null,
      child: Container(
        width: 100,
        height: 100,
        decoration: BoxDecoration(
          border: Border.all(
            color: canAddMore ? Colors.grey[400]! : Colors.grey[300]!,
            style: BorderStyle.solid,
          ),
          borderRadius: BorderRadius.circular(8),
          color: canAddMore ? Colors.grey[50] : Colors.grey[100],
        ),
        child: Icon(
          Icons.add_photo_alternate,
          size: 40,
          color: canAddMore ? Colors.grey[600] : Colors.grey[400],
        ),
      ),
    );
  }

  /// 构建图片项
  Widget _buildImageItem({
    File? imageFile,
    String? imageUrl,
    required VoidCallback onRemove,
  }) {
    return Stack(
      children: [
        Container(
          width: 100,
          height: 100,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.grey[300]!),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: imageFile != null
                ? Image.file(
                    imageFile,
                    fit: BoxFit.cover,
                  )
                : Image.network(
                    imageUrl!,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[200],
                        child: const Icon(
                          Icons.broken_image,
                          color: Colors.grey,
                        ),
                      );
                    },
                  ),
          ),
        ),
        Positioned(
          top: 4,
          right: 4,
          child: GestureDetector(
            onTap: onRemove,
            child: Container(
              width: 24,
              height: 24,
              decoration: const BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.close,
                color: Colors.white,
                size: 16,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示图片来源选择对话框
  void _showImageSourceDialog() {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            color: Colors.white,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 头部
              Container(
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(16),
                    topRight: Radius.circular(16),
                  ),
                  gradient: LinearGradient(
                    colors: [
                      _eventType.color.withOpacity(0.8),
                      _eventType.color.withOpacity(0.6),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                child: Row(
                  children: [
                    Icon(
                      Icons.image,
                      color: Colors.white,
                      size: 24,
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Text(
                        '选择图片来源',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Icon(
                        Icons.close,
                        color: Colors.white.withOpacity(0.8),
                        size: 20,
                      ),
                    ),
                  ],
                ),
              ),
              
              // 内容
              Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 拍照选项
                    InkWell(
                      onTap: () {
                        Navigator.of(context).pop();
                        _pickImage(ImageSource.camera);
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.grey[50],
                        ),
                        child: Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                color: _eventType.color.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Icon(
                                Icons.camera_alt,
                                color: _eventType.color,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '拍照',
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  const SizedBox(height: 2),
                                  Text(
                                    '使用相机拍摄新照片',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 16,
                              color: Colors.grey[400],
                            ),
                          ],
                        ),
                      ),
                    ),
                    
                    const SizedBox(height: 12),
                    
                    // 从相册选择选项
                    InkWell(
                      onTap: () {
                        Navigator.of(context).pop();
                        _pickImage(ImageSource.gallery);
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.grey[50],
                        ),
                        child: Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                color: _eventType.color.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Icon(
                                Icons.photo_library,
                                color: _eventType.color,
                                size: 24,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '从相册选择',
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  const SizedBox(height: 2),
                                  Text(
                                    '从手机相册中选择照片',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 16,
                              color: Colors.grey[400],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择图片
  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: source,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );
      
      if (image != null) {
        setState(() {
          _selectedImages.add(File(image.path));
        });
      }
    } catch (e) {
      print('选择图片失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('选择图片失败，请重试')),
      );
    }
  }

  /// 选择多张照片
  Future<void> _pickPhotos() async {
    try {
      final List<XFile> images = await _imagePicker.pickMultiImage(
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1920,
      );
      
      if (images.isNotEmpty) {
        setState(() {
          for (final image in images) {
            if (_selectedImages.length + _photoUrls.length < 9) {
              _selectedImages.add(File(image.path));
            }
          }
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('选择照片失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 拍照
  Future<void> _takePhoto() async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1920,
      );
      
      if (image != null) {
        setState(() {
          _selectedImages.add(File(image.path));
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('拍照失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 移除本地图片
  void _removeLocalImage(int index) {
    setState(() {
      _selectedImages.removeAt(index);
    });
  }

  /// 移除网络图片
  void _removeNetworkImage(int index) {
    setState(() {
      _photoUrls.removeAt(index);
    });
  }

  /// 选择事件日期
  Future<void> _selectEventDate(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _eventDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
    );
    
    if (picked != null) {
      setState(() {
        _eventDate = DateTime(
          picked.year,
          picked.month,
          picked.day,
          _eventTime.hour,
          _eventTime.minute,
        );
      });
    }
  }

  /// 选择事件时间
  Future<void> _selectEventTime(BuildContext context) async {
    final picked = await showTimePicker(
      context: context,
      initialTime: _eventTime,
    );
    
    if (picked != null) {
      setState(() {
        _eventTime = picked;
        _eventDate = DateTime(
          _eventDate.year,
          _eventDate.month,
          _eventDate.day,
          picked.hour,
          picked.minute,
        );
      });
    }
  }

  /// 保存事件
  Future<void> _saveEvent() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      try {
        // 构建事件时间
        final eventDateTime = DateTime(
          _eventDate.year,
          _eventDate.month,
          _eventDate.day,
          _eventTime.hour,
          _eventTime.minute,
        );

        // TODO: 上传本地图片到服务器，获取图片URL
        // 这里暂时使用占位符URL，实际项目中需要实现图片上传功能
        List<String> allPhotoUrls = List.from(_photoUrls);
        for (int i = 0; i < _selectedImages.length; i++) {
          // 这里应该调用图片上传API，获取真实的URL
          // 暂时使用占位符
          allPhotoUrls.add('https://via.placeholder.com/400x400?text=Image${i + 1}');
        }

        // 创建或更新事件
        DatelineEvent event;
        if (widget.eventToEdit != null) {
          event = widget.eventToEdit!.copyWith(
            eventTypeId: _eventType.id.toString(),
            title: _titleController.text.trim(),
            location: _locationController.text.trim().isEmpty 
                ? null 
                : _locationController.text.trim(),
            eventTime: eventDateTime,
            description: _descriptionController.text.trim().isEmpty 
                ? null 
                : _descriptionController.text.trim(),
            photoUrls: allPhotoUrls,
          );
        } else {
          event = DatelineEvent(
            eventTypeId: _eventType.id.toString(),
            title: _titleController.text.trim(),
            location: _locationController.text.trim().isEmpty 
                ? null 
                : _locationController.text.trim(),
            eventTime: eventDateTime,
            description: _descriptionController.text.trim().isEmpty 
                ? null 
                : _descriptionController.text.trim(),
            photoUrls: allPhotoUrls,
          );
        }

        // 调用 Provider 保存事件
        final datelineEventsNotifier = ref.read(datelineEventsProvider.notifier);
        final result = widget.eventToEdit != null
            ? await datelineEventsNotifier.updateEvent(event)
            : await datelineEventsNotifier.addEvent(event);

        if (result != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(widget.eventToEdit == null ? '事件创建成功' : '事件更新成功'),
              backgroundColor: Colors.green,
            ),
          );
          
          // 刷新数据：重新加载所有时间线事件和按类型过滤的事件
          ref.invalidate(datelineEventsProvider);
          ref.invalidate(datelineEventsByTypeProvider(null));
          
          // 关闭弹窗
          if (mounted) {
            Navigator.of(context).pop(result);
          }
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(widget.eventToEdit == null ? '事件创建失败' : '事件更新失败'),
              backgroundColor: Colors.red,
            ),
          );
        }
      } catch (e) {
        print('保存事件失败: $e');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('保存失败，请重试'),
            backgroundColor: Colors.red,
          ),
        );
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }
}